package com.execl.configuration;

import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;
import java.beans.PropertyVetoException;
import java.io.IOException;

@Configuration
@MapperScan(basePackages = "com.execl.dao", sqlSessionFactoryRef = "sqlSessionFactory")
public class DataSourceConfiguration {

	@Value("${spring.datasource.url}")
	private String url;
	@Value("${spring.datasource.username}")
	private String username;
	@Value("${spring.datasource.password}")
	private String password;
	@Value("${spring.datasource.driverClassName}")
	private String driverClassName;

	@Bean(name = "dataSource")
	@Primary
	public DataSource createDataSource() throws PropertyVetoException {

//		ComboPooledDataSource dataSource = new ComboPooledDataSource();
		HikariDataSource dataSource = new HikariDataSource();
		dataSource.setUsername(username);
		dataSource.setPassword(password);
		dataSource.setJdbcUrl(url+"&useAffectedRows=true");
		dataSource.setDriverClassName(driverClassName);

		// 关闭连接后不自动commit
		dataSource.setAutoCommit(false);

		return dataSource;

	}

	@Bean(name = "sqlSessionFactory")
	@Primary
	public SqlSessionFactoryBean createSqlSessionFactoryBean(@Qualifier("dataSource") DataSource dataSource)
			throws IOException {

		SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();

		sqlSessionFactoryBean.setConfigLocation(new ClassPathResource("mybatis-config.xml"));

		PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

		String packageSearchPath = PathMatchingResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX+"/mapper/**.xml";

		sqlSessionFactoryBean.setMapperLocations(resolver.getResources(packageSearchPath));

		sqlSessionFactoryBean.setDataSource(dataSource);

		return sqlSessionFactoryBean;

	}

	@Bean(name = "transactionManager")
	@Primary
	public DataSourceTransactionManager sentinelTransactionManager(@Qualifier("dataSource") DataSource dataSource) {
		return new DataSourceTransactionManager(dataSource);
	}

	@Bean(name = "sqlSessionTemplate")
	@Primary
	public SqlSessionTemplate sentinelSqlSessionTemplate(
			@Qualifier("sqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
		return new SqlSessionTemplate(sqlSessionFactory);
	}

}
